// userPageC/pages/shopBulk/shopBulk.js
const app = getApp(); 
const WXAPI = require("../../../api/api"); 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1,
      // 是否显示左上角图标   1表示显示    0表示不显示 
      title: '门店团购',
      // 导航栏 中间的标题
      textColor: '#222',
      // 标题颜色
      bgColor: '#fff',
      // 导航栏背景颜色
      isloading: true,
      isColor: true 
    },
    shopImgList:[
      {id: 0,url:'/images/banner.png'},
      {id: 1,url:'/images/banner.png'},
      {id: 2,url:'/images/banner.png'},
      {id: 3,url:'/images/banner.png'},
    ],
    imgHttp: app.globalData.imgHttp,
    shopId: '',
    shopLnt: app.globalData.lnt,
    shopLat: app.globalData.lat,
    swiperindex: 0,
    phoneShow: false,
    shopData: {},
    bulkList: [],
    isPull: true,//是否刷新
    lodingtype: 1,//加载状态（0：加载中  1：加载完成没有更多）
    merchantId: '',
    name: '',
    pageSize: 10,
    pageNum: 1,
    orderNum: {},
    evaluateList:[],
    evaluateTotal: 0,
    starnum: 5,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    var shopId = options.shopId
    // var shopId = '1421288563226120193'
    this.setData({  
      shopId: shopId,
    })
    await this.getDetail()
    await this.getList()
    await this.getEvaluateList()
  },
  //详情
  getDetail(){
    return new Promise((resolve,reject) =>{
      var data = {
        shopId: this.data.shopId,
        shopLnt: this.data.shopLnt,
        shopLat: this.data.shopLat,
      }
      WXAPI.merchantInfo(data,res => {
        const data = res.result
        if(res.code == 200){
          this.setData({
            shopData: res.result,
            merchantId: res.result.merchantId,
            phoneList: data.phone.split(','),
            
          })
          resolve()
        }
      })
    })    
  },
  //团购列表
  getList(){
    return new Promise((resolve,reject) => {
      const that = this;
      wx.showLoading({
        title: '加载中',
        mask: true
      });
      var data = {
        name: this.data.name,
        merchantId: this.data.merchantId,
        pageSize: this.data.pageSize,
        pageNum: this.data.pageNum,
      }
      WXAPI.merchantGrouponList(data, res => {
        const {size,total,records} = res.result;
        var list = [];
        var bulkList = this.data.bulkList;
        if (res.code === 200) {
          if (this.data.pageNum >= Math.ceil(total / size)) {
            this.setData({
              lodingtype: 1,
              isPull: false
            });
          } else {
            this.setData({
              lodingtype: 0,
              isPull: true
            });
          }

          wx.hideLoading();
          list = records, this.setData({
            bulkList: bulkList.concat(list)
          });
          resolve()
        }
      });
    })
  },
  //订单数量
  getOrderNum(){
    return new Promise((resolve,reject) =>{
      // var data = {
      //   merchantId: this.data.merchantId,
      // }
      WXAPI.orderNum('',res => {
        const data = res.result
        if(res.code == 200){
          this.setData({
            orderNum: data
          })
          resolve()
        }
      })
    })
  },
  // 套餐详情
  handleCard(e){
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/userPageC/pages/abulkDetail/abulkDetail?id='+id,
    });
  },
  //打开电话弹窗
  bindchangeSwiper(e) {
    this.setData({
      swiperindex: e.detail.current
    })
  },
  //打开电话弹窗
  handlePhoneShow() {
    this.setData({
      phoneShow: !this.data.phoneShow
    });
  },
  //拨打电话
  freeTell(e) {
    var phone = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: phone
    });
  },
  //导航到地方
  getLocation: function () {
    const that = this;
    wx.getSetting({
      success: res => {
        var statu = res.authSetting;

        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          // console.log('authSetting:status:拒绝授权后再次进入重新授权', res.authSetting['scope.userLocation'])
          wx.showModal({
            title: '',
            content: '需要获取你的地理位置才能进行导航，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none'
                });
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    // console.log('dataAu:success', dataAu)
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      //再次授权，调用wx.getLocation的API
                      that.newgetLocation(dataAu, callback);
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none'
                      });
                    }
                  }
                });
              }
            }
          });
        } else {
          that.newgetLocation();
        }
      }
    });
  },
  newgetLocation() {
    const storesData = this.data.shopData;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        wx.openLocation({
          //​使用微信内置地图查看位置。
          latitude: storesData.shopLat,
          //要去的纬度-地址
          longitude: storesData.shopLnt,
          //要去的经度-地址
          name: storesData.merchantName,
          address: storesData.locateAddress
        });
      }
    });
  },
  //去抢购
  handlePay(e){
    const id = e.currentTarget.dataset.id
    const limitType = e.currentTarget.dataset.limittype
    const limitCount = e.currentTarget.dataset.limitcount
    if(limitType == 2 && limitCount){

    }
    wx.navigateTo({
      url: '/userPageC/pages/confirmOrder/confirmOrder?grouponId='+id,
    });
  },
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function (res) {
  //   var shopId = this.data.shopId
  //   return {
  //     title: '门店团购',
  //     path: 'userPageB/pages/shopBulk/shopBulk?shopId='+shopId,
  //   }
  // },
  //评价列表
  getEvaluateList(){
    const data = {
      merchantId: this.data.merchantId,
      pageNum: 1,
      pageSize: 3,
    }
    WXAPI.getEvaluateList(data,(res) => {
      this.data.evaluateList = res.result.records.map(item => {
        item.image = JSON.parse(item.image)
        item.totalPoints = item.totalPoints / 2
        return item
      })  
      console.log('this.data.evaluateList',this.data.evaluateList)
      this.setData({
        evaluateList: this.data.evaluateList,
        
        evaluateTotal: res.result.total
      })
    })
  },
  //更多评价
  handleEva(){
    wx.navigateTo({
      url: '/userPageB/pages/evaluationList/evaluationList?merchantId='+this.data.merchantId,
    })
  },
  showImg:function(e){
    var that = this;
    var shopImgList = e.currentTarget.dataset.img
    console.log('shopImgList',shopImgList)
    let imglists = shopImgList.map((item, index)=>{
      item = that.data.imgHttp+item
      return item
    })
    wx.previewImage({
        urls: imglists,
        current: that.data.imgHttp + shopImgList[e.currentTarget.dataset.index]
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
})